package demo02;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket;

public class NewFileUploadClient {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 8888);
                BufferedInputStream bufferedInputStream = new BufferedInputStream( // 使用缓冲流输入，提高效率
                        new FileInputStream("file\\土墩墩.jpg"))) {
            BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream()); // 输出流：向服务端发送信息，数据量大，通过缓冲流提高效率
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len); // 上传数据
            }
            socket.shutdownOutput(); // 数据上传完毕后关闭输出流，同时能够将结束标记加进去
            InputStream inputStream = socket.getInputStream(); // 输入流：接收服务端的回写信息
            while ((len = inputStream.read(bytes)) != -1) { // 接收回写数据
                System.out.println(new String(bytes, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
